//
//  DetailUtil.m
//  cactus
//
//  Created by li hongdan on 12-1-1.
//  Copyright (c) 2012年 ifeng. All rights reserved.
//

#import "DetailUtil.h"
#import <CoreText/CoreText.h>

@implementation DetailUtil

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

+(CGSize)lineByWidth:(NSString *)str Width:(CGFloat)width Font:(UIFont *)font{
    if (str) {
      
      return [DetailUtil lineByWidth:str Width:width Font:font lineHeight:font.lineHeight];
    }
    return CGSizeZero;
}

+(CGSize)lineByWidth:(NSString *)str Width:(CGFloat)width Font:(UIFont *)font lineHeight:(int)lineHeight{
    
    if (str) {
      int line_num=[DetailUtil lineNumByWidth:str Width:width Font:font];;
   
      
     
      float gap=lineHeight-font.lineHeight;
      CGSize size={width,(line_num*font.lineHeight+(line_num)*gap)};
      return size;
    }
    return CGSizeZero;
}

+(NSInteger)lineNumByWidth:(NSString *)str Width:(CGFloat)width Font:(UIFont *)font{
    
    if (str) {
      int line_num=0;
      CTFontRef cffont = CTFontCreateWithName((__bridge CFStringRef)font.fontName , 
                                              font.pointSize, 
                                              NULL);
      
      NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                  (__bridge id)cffont, (id)kCTFontAttributeName,
                                  [UIColor blackColor].CGColor, kCTForegroundColorAttributeName,
                                  nil];
      
      NSAttributedString *attributedString = [[NSAttributedString alloc] 
                                               initWithString:str 
                                               attributes:attributes];
      CFRelease(cffont);
      
      CTTypesetterRef typeSetter = CTTypesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attributedString);
      
      // 每行的字数
      int offsetByline=0;
      int startIndex = 0;
      do {
        offsetByline=CTTypesetterSuggestLineBreak(typeSetter,
                                                  startIndex, 
                                                  width);
        
        if (offsetByline>0) {
          startIndex+=offsetByline;
          line_num++;
        }
      }while (offsetByline>0);
      
      CFRelease(typeSetter);
      return line_num;

    }
    return 0;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
